package com.betting.controller;

import com.betting.entity.BetRecord;
import com.betting.service.BetRecordService;
import com.betting.service.ExportService;
import com.betting.dto.StreakStats;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.net.URI;

@Controller
@RequestMapping("/export")
@RequiredArgsConstructor
public class ExportController {

    private final ExportService exportService;
    private final BetRecordService betRecordService;

    @GetMapping("/page")
    public String exportPage() {
        return "bet/export";
    }

    @GetMapping("/streak")
    public ResponseEntity<byte[]> exportStreak(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            HttpServletRequest request) {
        
        // 检查会话
        HttpSession session = request.getSession(false);
        if (session == null) {
            // 返回重定向响应
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(URI.create(request.getContextPath() + "/login"));
            return ResponseEntity.status(HttpStatus.FOUND)
                    .headers(headers)
                    .build();
        }
        
        try {
            // 如果没有提供日期，使用默认值
            if (startDate == null) {
                startDate = LocalDate.now().minusMonths(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            // 获取统计数据
            StreakStats stats = betRecordService.getStreakStats(startDate, endDate);
            if (stats == null) {
                return ResponseEntity.noContent().build();
            }
            
            // 转换为Map
            Map<String, Object> statsMap = new HashMap<>();
            statsMap.put("maxWinStreak", stats.getMaxWinStreak());
            statsMap.put("maxLoseStreak", stats.getMaxLoseStreak());
            statsMap.put("hitRate", stats.getHitRate());
            statsMap.put("streakDetails", stats.getStreakDetails());
            
            // 生成Excel
            byte[] excelBytes = exportService.exportStreakToExcel(statsMap);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            String filename = String.format("streak_%s_%s.xlsx", 
                startDate.format(DateTimeFormatter.ISO_DATE),
                endDate.format(DateTimeFormatter.ISO_DATE));
            headers.setContentDispositionFormData("attachment", filename);
            headers.setContentLength(excelBytes.length);
            
            return ResponseEntity.ok()
                .headers(headers)
                .body(excelBytes);
            
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("导出失败：" + e.getMessage()).getBytes());
        }
    }

    @GetMapping("/daily")
    public ResponseEntity<byte[]> exportDaily(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        try {
            // 如果没有提供日期，使用默认值
            if (startDate == null) {
                startDate = LocalDate.now().minusMonths(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            // 获取统计数据
            Map<String, Object> stats = betRecordService.getDailySummary(startDate);
            byte[] excelBytes = exportService.exportDailyToExcel(stats);
            return buildExcelResponse(excelBytes, "daily_" + startDate.toString() + "_" + endDate.toString() + ".xlsx");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }

    @GetMapping("/monthly")
    public ResponseEntity<byte[]> exportMonthly(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        try {
            // 如果没有提供日期，使用默认值
            if (startDate == null) {
                startDate = LocalDate.now().minusMonths(1);
            }
            if (endDate == null) {
                endDate = LocalDate.now();
            }
            
            // 获取统计数据
            Map<String, Object> stats = betRecordService.getMonthlySummary(startDate, endDate);
            byte[] excelBytes = exportService.exportMonthlyToExcel(stats);
            return buildExcelResponse(excelBytes, "monthly_" + startDate.toString() + "_" + endDate.toString() + ".xlsx");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }

    private ResponseEntity<byte[]> buildExcelResponse(byte[] content, String filename) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        headers.setContentDispositionFormData("attachment", filename);
        headers.setContentLength(content.length);
        headers.setCacheControl("no-cache, no-store, must-revalidate");
        headers.setPragma("no-cache");
        headers.setExpires(0);
        
        return ResponseEntity.ok()
            .headers(headers)
            .body(content);
    }

    @GetMapping("/excel")
    public ResponseEntity<byte[]> exportToExcel(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) throws Exception {
        
        if (startDate == null) {
            startDate = LocalDate.now().minusMonths(1);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }
        
        // 验证日期范围
        if (startDate.isAfter(endDate)) {
            throw new IllegalArgumentException("开始日期不能晚于结束日期");
        }
        
        // 限制导出数据范围，比如最多导出一年的数据
        if (startDate.plusYears(1).isBefore(endDate)) {
            throw new IllegalArgumentException("导出数据范围不能超过一年");
        }
        
        System.out.println("接收导出请求：startDate=" + startDate + ", endDate=" + endDate);
        
        List<BetRecord> records = betRecordService.getRecordsByDateRange(startDate, endDate);
        byte[] excelContent = exportService.exportToExcel(records);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "betting_records.xlsx");
        
        return ResponseEntity.ok()
                .headers(headers)
                .body(excelContent);
    }
} 